<template>
  <el-card>
    <span slot="header">修改密码</span>
    <el-form
      :model="formData"
      label-width="82px"
      class="form"
      :rules="rules"
      size="small"
      status-icon
      ref="formRef"
    >
      <!-- 原密码 -->
      <el-form-item label="原密码" prop="password">
        <el-input v-model="formData.password"></el-input>
      </el-form-item>
      <!-- 新密码 -->
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="formData.newPassword"></el-input>
      </el-form-item>
      <!-- 确认新密码 -->
      <el-form-item label="确认新密码" prop="okPassword">
        <el-input v-model="formData.okPassword"></el-input>
      </el-form-item>
      <!-- 确定&重置 -->
      <el-form-item>
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import {editPWDReq} from '@/api/user'

export default {
  data() {
    // 原密码
    const checkPassword = (rules, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码！'))
        //2 正则校验
      } else if (!/^[a-zA-Z0-9_-]{6,10}$/.test(value)) {
        callback(new Error('英文、数字、下划线 6至10位'))
      } else {
        callback()
      }
    }
    // 新密码
    const checkNewPassword = (rules, value, callback) => {
      if (value === '') {
        callback(new Error('密码不能为空'))
      } else if (value === this.formData.password) {
        callback(new Error('新密码不能跟原密码一样'))
      } else if (!/^[0-9a-zA-Z_-]{6,10}$/.test(value)) {
        callback(new Error('请输入由数字、英文、英文下划线及-组成的6-10为字符'))
      } else {
        callback()
      }
    }
    // 确认新密码
    const checkOkPassword = (rules, value, callback) => {
      if (value === '') {
        callback(new Error('新密码不能为空'))
      } else if (value !== this.formData.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      formData: {
        password: '',
        newPassword: '',
        okPassword: '',
      },
      rules: {
        password: [{validator: checkPassword, trigger: 'blur'}],
        newPassword: [{validator: checkNewPassword, trigger: 'blur'}],
        okPassword: [{validator: checkOkPassword, trigger: 'blur'}],
      },
    }
  },
  methods: {
    //提交表单
    submit() {
      this.$refs.formRef.validate(async valid => {
        // console.log('valid :>> ', valid)
        let newPwd = this.formData.newPassword // console.log('newPwd :>> ', newPwd);
        let res = await editPWDReq({newPwd})
        let {code,msg}=res.data
        if(code===0){
          console.log('msg :>> ', msg);
          //跳转
          this.$router.push('/login')
        }
        
      })
    },
    //重置表单
    reset() {
      this.$refs.formRef.resetFields()
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep.el-input {
  width: 310px;
}
// :deep(.el-input) {
//   width: 310px;
// }
</style>
